import React from "react"
import Control from "../components/Control"
import BoardArea from "../components/BoardArea";
import { deepClone } from "../utils/func"
import { BLACK_CHESS ,WHITE_CHESS} from "../constants/checkboard"
import isSuccess from "../utils/success"

export default class Game extends React.Component {
    constructor(props){
        super(props)
        // 所有棋格
        const checkerboard = new Array(15).fill(new Array(15).fill(0));
        console.log(checkerboard);
        this.state= {
            checkerboard,
            // 第一步下黑棋
            isBlack:true,
            isFinish: false
        }
        // 落棋记录
        this.records = [];
    }
    // 落子
    handleColClick(row,col){
        console.log(row,col);
        // 深度拷贝
        const state = deepClone(this.state)
        if(state.isFinish){
            return
        }
        // 判断是黑白棋
        state.checkerboard[row][col] = state.isBlack ? BLACK_CHESS :WHITE_CHESS;
        if(isSuccess(state.checkerboard,row,col)){
            alert(`${state.isBlack?'黑棋':'白棋'}获胜！` );
        }
        // 将当前棋子添加到记录中
        this.records.push(this.state);
        this.setState({
            checkerboard:state.checkerboard,
                isBlack: !state.isBlack
        })

    }
    // 重新开始
    handleRest() {
        const checkerboard = new Array(15).fill(new Array(15).fill(0));
        this.setState({
            checkerboard,
            // 第一步下黑棋
            isBlack: true,
            isFinish: false
        })
        this.records = [];
    }
    // 悔棋处理
    handleRegret () {
        const state = deepClone(this.records.pop()) 
        this.setState({
            ...state
        })
    }
    render() {
        const height = window.innerHeight;
        return (
            <div className="Game" style={{ minHeight: height }}>
                <Control onRest={this.handleRest.bind(this)}  onRegret={this.handleRegret.bind(this)}/>
                <BoardArea checkerboard={this.state.checkerboard} onColClick={this.handleColClick.bind(this)}/>
            </div>
        );
    }
}